const process = require('process');
const path = require('path');
const fs = require('fs');
const pipelines = JSON.parse(process.env['CI_PIPELINES'] || '{}');
const namespaces = JSON.parse(process.env['CI_NS_SETTING'] || '{}');
const fetching = JSON.parse(process.env['CI_FETCHING'] || '{}');
const autopipeline = JSON.parse(process.env['CI_AUTO_PIPELINE'] || '{}');
const preparation = JSON.parse(process.env['CI_PREPARATION'] || '{}');
const buildOptions = JSON.parse(process.env['CI_BUILD_OPTIONS'] || '{}');
const self = process.env['CI_PROJECT_PATH'];
const ref = process.env['CI_COMMIT_REF_NAME'];
const action = process.argv[2];
const branchTagMapping = JSON.parse(process.env.CI_BRANCH_TAGS || '{}');

switch (action) {
  case "triggers":
    const jobs = pipelines[self];
    if (jobs) {
      let set = new Set();
      for (const np of jobs) {
        for (const [rule, branch] of Object.entries(branchTagMapping)) {
          if (new RegExp(rule).test(ref)) {
            set.add(`${np} ${branch}`);
            break;
          }
        }
      }
      for (const t of set) {
        console.log(t);
      }
    }
    break;
  case "namespaces": {
    const targets = namespaces[self];
    if (targets) {
      for (const [rule, candidates] of Object.entries(targets)) {
        if (new RegExp(rule).test(ref)) {
          console.log(candidates);
          break;
        }
      }
    }
    break;
  }
  case "fetching": {
    if (fetching && fetching[self]) {
      const fetches = fetching[self];
      for (const src of Object.keys(fetches)) {
        const file = fetches[src].replace('${CI_PROJECT_DIR}', process.env.CI_PROJECT_DIR);
        const dir = path.dirname(file);
        if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
        console.log(`curl -vskS "${src}" -o "${file}"`);
      }
    }
    break;
  }
  case "autopipeline": {
    console.log(true == autopipeline[self] || undefined == autopipeline[self]);
    break;
  }
  case "preparation": {
    console.log(preparation[self] || "echo Nothing need to do");
    break;
  }
  case "options": {
    console.log(buildOptions[self] || "");
    break;
  }
}

process.exit(0)